<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false">
        <n-space vertical justify="center">
          <n-steps :current="currentTab" :status="currentStatus">
            <n-step title="基本信息" description="填写流程模型基本信息" />
            <n-step title="流程表单设计" description="设计流程表单" />
            <n-step title="流程设计" description="设计流程" />
            <n-step title="完成" description="恭喜您完成流程设计" />
          </n-steps>
        </n-space>
      </n-card>
    </div>

    <n-card :bordered="false" class="mt-4 proCard">
      <div class="base-form" v-if="currentTab === 1" @next-step="nextStep">
        <div class="base-form-item">
          <n-form
            :model="fromValues"
            :rules="rules"
            ref="formRef"
            label-placement="top"
            :label-width="120"
            class="py-4"
            style="width: 100%"
          >
            <n-form-item label="流程模型图标" path="flowModelIcon">
              <n-popover
                placement="bottom"
                trigger="click"
                @update:show="handleUpdateShow"
              >
                <template #trigger>
                  <n-avatar
                    class="flowModelIcon"
                    round
                    :size="48"
                    :src="fromValues.flowModelIcon"
                  />
                </template>
                <n-grid :x-gap="12" :y-gap="8" :cols="4">
                  <n-grid-item v-for="item in flowIcon" :key="item.name">
                    <n-avatar
                      @click="cheangeIcon(item.icon)"
                      class="flowModelIcon"
                      round
                      :size="48"
                      :src="item.icon"
                    />
                  </n-grid-item>
                </n-grid>
              </n-popover>
            </n-form-item>
            <n-form-item label="流程模型名称" path="flowModelName">
              <n-input
                maxlength="100"
                show-count
                placeholder="请输入流程模型名称"
                v-model:value="fromValues.flowModelName"
              />
            </n-form-item>
            <n-form-item label="流程模型分组" path="flowModelGroup">
              <n-select
                v-model:value="fromValues.flowModelGroup"
                placeholder="请选择流程模型分组"
                :options="groupOptions"
              />
            </n-form-item>
            <n-form-item label="流程模型类型" path="flowModelType">
              <n-select
                v-model:value="fromValues.flowModelType"
                placeholder="请选择流程模型类型"
                :options="typeOptions"
              />
            </n-form-item>
            <n-form-item label="流程模型完成方式" path="flowModelCompletionMethod">
              <n-select
                v-model:value="fromValues.flowModelCompletionMethod"
                placeholder="请选择流程模型完成方式"
                :options="modelSetting"
              />
            </n-form-item>
            <n-form-item
              label="流程模型指定通过人"
              path="flowModelAdmin"
              v-if="fromValues.flowModelCompletionMethod === 3"
            >
              <n-select
                v-model:value="fromValues.flowModelAdmin"
                placeholder="请选择流程模型指定通过人"
                :options="modelAdmin"
              >
                <template #action>
                  <div>
                    <div style="margin-bottom: 10px">
                      <n-input
                        placeholder="输入用户姓名回车搜索"
                        clearable
                        @change="handleChange"
                      >
                        <template #prefix>
                          <n-icon :component="SearchOutlined" />
                        </template>
                        <template #suffix>
                          <n-icon :component="EnterOutlined" />
                        </template>
                      </n-input>
                    </div>
                    <BasicTable
                      :columns="userColumns"
                      :request="loadDataTable"
                      :row-key="(row) => row.id"
                      ref="actionRef"
                      id="moss-basicTable"
                      :bordered="false"
                      :actionColumn="actionColumn"
                      :max-height="200"
                      :showTopOps="false"
                    >
                      <template #action>
                        <TableAction />
                      </template>
                    </BasicTable>
                  </div>
                </template>
              </n-select>
            </n-form-item>
            <n-form-item label="流程模型说明" path="flowModelDesc">
              <n-input
                maxlength="300"
                show-count
                type="textarea"
                :autosize="{
                  minRows: 3,
                  maxRows: 5,
                }"
                v-model:value="fromValues.flowModelDesc"
                filterable
                placeholder="请输入流程模型说明"
              />
            </n-form-item>
          </n-form>
        </div>
      </div>
      <div v-if="currentTab === 2" @next-step="nextStep" @prevStep="prevStep">
        <div style="height: 65vh">
          <FormDesign ref="childRef" />
        </div>
      </div>
      <div v-if="currentTab === 3" @next-step="nextStep" @prevStep="prevStep">
        <flowDesign ref="flowDesignRef" :flowData="fromValues.flowData" />
      </div>
      <div v-if="currentTab === 4" @prev-step="prevStep" @finish="finish">
        <n-result
          status="success"
          title="操作成功"
          description="流程已发布"
          class="step-result"
        >
          <template #footer>
            <div class="flex justify-center">
              <n-button type="primary" @click="navigateToRoute"
                >返回流程模型列表</n-button
              >
            </div>
          </template>
        </n-result>
      </div>
      <div class="flex justify-center" style="margin-top: 15px">
        <n-space>
          <n-button
            v-if="currentTab !== 4 && currentTab !== 3"
            type="primary"
            @click="nextStep"
            >下一步</n-button
          >
          <n-button
            v-if="currentTab === 3"
            type="primary"
            @click="nextStep"
            :loading="formBtnLoading"
            >提交并发布</n-button
          >
          <n-button v-if="currentTab !== 1 && currentTab !== 4" @click="prevStep"
            >上一步</n-button
          >
        </n-space>
      </div>
    </n-card>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, reactive,h } from 'vue';
import { useRouter } from 'vue-router';
import { type FormRules, useMessage } from 'naive-ui';
import flowDesign from '../flowDesign.vue';
import FormDesign from '@/components/naiveui/FormDesign.vue';
import { page } from '@/api/flow/flowGroup';
import { save, update } from '@/api/flow/flowModel';
import { ResultEnum } from '@/enums/httpEnum';
import { detail } from '@/api/flow/flowModel';
import { userColumns } from "./userColumns";
import { BasicTable, TableAction } from "@/components/Table";
import { usersPages,usersById } from '@/api/system/user';
import { PlusOutlined,EnterOutlined,SearchOutlined } from "@vicons/antd";
const message = useMessage();
const childRef = ref<any>(null);
const flowDesignRef = ref<InstanceType<typeof flowDesign> | null>(null);
// import GenerateForm from '../../../components/naiveui/components/generate/GenerateForm.vue';
const formRef: any = ref(null);
const currentTab = ref(1);
const currentStatus = ref<string>('process');
const router = useRouter();
const groupOptions = ref([]);
const typeOptions = ref([{ label: '工作流', value: 1 }, { label: '协同作战任务', value: 2 }]);
const popoverShow = ref<boolean>(false);
const modelSetting = ref([{ label: '全部通过', value: 1 }, { label: '少数服从多数，多数通过流程通过', value: 2 },
    { label: '指定人通过流程通过', value: 3 }, { label: '流程模型配置的有一个节点审批不通过直接结束流程', value: 4 }
]);
const flowIcon = ref([{ name: '工作', icon: 'https://qxht.xiaomy.net/file/icon/flow/flowTask.png' },
{ name: '任务', icon: 'https://qxht.xiaomy.net/file/icon/flow/flowHb.png' }]);
const modelAdmin = ref<any[]>([]);
const formBtnLoading = ref<boolean>(false);
const actionRef = ref();
const defaultValueRef = () => ({
    // 流程模型名称
    flowModelName: '',
    // 流程模型说明
    flowModelDesc: '',
    // 流程模型分组
    flowModelGroup: null,
    // 流程模型类型
    flowModelType: null,
    // 流程模型动态表单
    flowModelForm: '',
    // 流程模型完成方式
    // 1全部通过
    // 2少数服从多数，多数通过流程通过
    // 3指定人通过流程通过
    // 4流程模型配置的有一个节点审批不通过直接结束流程
    flowModelCompletionMethod: null,
    // 流程模型管理员（流程模型完成方式为指定人通过，流程通过时必填，并且只能选择一个管理员，且该管路员是其中一个审批人）
    flowModelAdmin: null,
    // 流程数据
    flowData: '',
    // 流程图标
    flowModelIcon: 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg'
});
let fromValues = reactive(defaultValueRef());
const rules: FormRules = {
    flowModelName: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入流程模型名称',
    },
    flowModelGroup: {
        type: 'number',
        required: true,
        trigger: ['blur', 'select'],
        message: '请选择流程模型分组',
    },
    flowModelAdmin: {
        type: 'number',
        required: true,
        trigger: ['blur', 'select'],
        message: '请选择流程模型管理员',
    },
    flowModelType: {
        type: 'number',
        required: true,
        trigger: ['blur', 'select'],
        message: '请选择流程模型类型',
    },
    flowModelCompletionMethod: {
        type: 'number',
        required: true,
        trigger: ['blur', 'select'],
        message: '请选择流程模型完成方式',
    },
};
const searchName = ref<string>('');
const loadDataTable = async (res: any) => {
  return await usersPages({ ...{name:searchName.value}, ...res,...{showTenant:true} });
};
const handleChange =(v: string)=> {
  searchName.value = v;
  reloadTable();
}
const actionColumn = reactive({
  title: "操作",
  key: "action",
  fixed: "right",
  render(record) {
    return h(TableAction as any, {
      style: "text",
      actions: createActions(record),
    });
  },
});
function createActions(record) {
  return [
    {
      label: "选择",
      type: "primary",
      icon: PlusOutlined,
      onClick: onCheckedRow.bind(null, record),
      ifShow: () => {
        return true;
      },
    },
  ];
}
function onCheckedRow(record: Recordable) {
  fromValues.flowModelAdmin = record.id;
  modelAdmin.value = [{ label: record.name, value: record.id }];
}
function reloadTable() {
  actionRef.value.reload();
}
const getFormJson = () => {
    const data = childRef?.value?.getJson();
    console.log('datadata', JSON.stringify(data));
    fromValues = Object.assign(fromValues, { flowModelForm: JSON.stringify(data) });
}
/**
 * 修改流程模型数据时设置动态表单数据
 */
const setFormJson = () => {
    message.loading('表单初始化中...', {
        duration: 500,
        onAfterLeave: async () => {
            if (currentTab.value === 2 && childRef?.value !== null) {
                childRef?.value?.setJson(JSON.parse(fromValues.flowModelForm));
            }
        }
    })
}
/**
 * 提交表单
 */
const submitForm = async () => {
    graphData();
    console.log('fromValues', fromValues);
    formBtnLoading.value = true;
    const id = router.currentRoute.value.params.id;
    const data = id === '0'?await save(fromValues):await update(fromValues);
    if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.msg + '-' + resultMsg);
        formBtnLoading.value = false;
    }
    if (data.code === ResultEnum.SUCCESS) {
        message.success(data.msg);
        formBtnLoading.value = false;
    }
}
const graphData = () => {
    const data = flowDesignRef?.value?.getGraphData();
    console.log('graphData', data);
    fromValues = Object.assign(fromValues, { flowData: JSON.stringify(data) });
}
const nextStep = () => {
    if (currentTab.value === 1) {
        formRef.value.validate(async (errors) => {
            if (!errors) {
                currentTab.value += 1;
                const id = router.currentRoute.value.params.id;
                if (id !== '0') {
                    setFormJson();
                }
            }
        });
    } else if (currentTab.value === 2) {
        getFormJson();
        currentTab.value += 1;
    } else if (currentTab.value === 3) {
        submitForm();
        currentTab.value += 1;
    }
}

const prevStep = () => {
    if (currentTab.value > 1) {
        currentTab.value -= 1;
        if(currentTab.value === 2){
            setFormJson();
        }
    }
}

const finish = () => {
    currentTab.value = 1;
}
const navigateToRoute = () => {
    router.go(-1);
}
const cheangeIcon = (icon: string) => {
    fromValues.flowModelIcon = icon;
}
const handleUpdateShow = () => {
    popoverShow.value = !popoverShow.value;
}
onMounted(async () => {
    const group = await page({});
    groupOptions.value = group.records.map(item => ({ label: item.groupName, value: item.id }));
    const id = router.currentRoute.value.params.id;
    if (id !== '0') {
        const flow = await detail({ id: id });
        fromValues = Object.assign(fromValues, flow);
        if(flow.flowModelAdmin){
            const flowAdmin = await usersById({ id: flow.flowModelAdmin });
            modelAdmin.value = [{ label: flowAdmin.name, value: flowAdmin.id }];
        }
    }
})
</script>
<style scoped>
.base-form {
  display: flex;
  justify-content: center;
}

.base-form-item {
  width: 30%;
}

.flowModelIcon:hover {
  cursor: pointer;
}
</style>
